/*
 * Copyright (c) 2011 Imre Fazekas.
 * All rights reserved.
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 * Neither the name of the Brillien nor the names of its
 * terms and concepts may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package com.vii.brillien.ignition.transport.mq;

import com.rabbitmq.client.QueueingConsumer;
import com.vii.brillien.ignition.BrillienContext;
import com.vii.brillien.ignition.transport.BrillienCommunication;
import com.vii.brillien.ignition.transport.BrillienMediator;
import com.vii.brillien.kernel.BrillienException;
import com.vii.brillien.kernel.axiom.transport.Communication;
import com.vii.brillien.kernel.axiom.transport.MessageProcessor;
import com.vii.streamline.services.json.JsonServices;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;

/**
 * Mediator implementing an in-memory "transport layer".
 */
public class MqMediator extends BrillienMediator<QueueingConsumer.Delivery> {

    /**
     * Name of the queue listening on.
     */
    protected String                                                            queuename;

    /**
     * Map of queue to catch responses.
     */
    protected ConcurrentHashMap<String, LinkedBlockingQueue<BrillienCommunication>>   responseQueues;

    {
        responseQueues = new ConcurrentHashMap<String, LinkedBlockingQueue<BrillienCommunication>>();

        addMessageProcessorType( MqResponseListener.class, this );
    }

    public class MqResponseListener implements MessageProcessor<BrillienCommunication> {
        private BrillienCommunication comm;
        @Override
        public void init(BrillienCommunication comm) {
            this.comm = comm;
        }

        @Override
        public void run() {
            BrillienContext.basicLog(Level.FINE, mediatorEntity() + ":: " + " processor received communication: " + comm);
            if( comm.getMessageType() == Communication.TYPE_RESULT || comm.getMessageType() == Communication.TYPE_ERROR ){
                if( responseQueues.containsKey( comm.getOriginalId() ) ){
                    try{
                        responseQueues.get( comm.getOriginalId() ).offer(comm);
                    } catch (Exception e){ e.printStackTrace(); }
                }
            }
        }
    }

    public MqMediator() {
    }

    public MqMediator(String queuename) {
        this.queuename = queuename.toLowerCase();
    }

    /**
     * Getter method for field queuename
     */
    public String getQueuename() {
        return queuename;
    }

    /**
     * Setter method for field queuename
     */
    public void setQueuename(String queuename) {
        this.queuename = queuename.toLowerCase();
    }

    @Override
    public MqCommunication newCommunication() throws BrillienException {
        return new MqCommunication();
    }

    @Override
    public void connect() throws BrillienException {
        MqStation.registerMediator( queuename, this );
        BrillienContext.basicLog(Level.FINE, mediatorEntity() + ":: " + "Connected.");

        startListening();
    }

    @Override
    public void disconnect() throws BrillienException {
        MqStation.unregisterMediator( queuename );

        BrillienContext.basicLog(Level.FINE, mediatorEntity() + ":: " + "Disconnected.");
    }

    @Override
    public void startListening() throws BrillienException {
        BrillienContext.basicLog(Level.FINE, mediatorEntity() + ":: " + "Started listening...");
    }

    @Override
    public String mediatorEntity() {
        return queuename;
    }

    @Override
    public BrillienCommunication sendCommunication(long timeout, HashMap<String, Object> properties, BrillienCommunication comm) throws BrillienException {
        try {
            final LinkedBlockingQueue<BrillienCommunication> queue = new LinkedBlockingQueue<BrillienCommunication>(1);

            if (comm.getMessageType() == Communication.TYPE_GET)
                responseQueues.putIfAbsent( comm.getId(), queue );

            MqStation.publish( comm );

            BrillienContext.basicLog(Level.FINE, mediatorEntity() + ":: " + "Message sent " + comm);

            BrillienCommunication response = null;

            if (comm.getMessageType() == Communication.TYPE_GET) {
                BrillienContext.basicLog( Level.FINE, mediatorEntity() + ":: " + "waiting for response for " + comm );

                try {
                    response = queue.poll(timeout, TimeUnit.MILLISECONDS);

                    BrillienContext.basicLog( Level.FINE, mediatorEntity() + ":: " + "response received " + response + " to " + comm );

                    if (response == null)
                        throw new BrillienException( "No response from server for communication: " + comm );
                    else if (response.getMessageType() == Communication.TYPE_ERROR){
                        throw new BrillienException( response.getErrorCode(), response.getResponse().toString(), response.getErrorValue() );
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally{
                    responseQueues.remove( comm.getId() );
                }
            }
            return response;
        } catch (BrillienException e) {
            throw e;
        } catch (Exception e) {
            throw new BrillienException(e);
        }
    }

}
